import { ethers, utils } from 'ethers'
export async function generateWallet () {
  const main = async () => {
    // 1. 生成随机助记词
    const mnemonic = utils.entropyToMnemonic(utils.randomBytes(32))
    // 创建 HDNode 钱包变量
    const HDNode = ethers.utils.HDNode.fromMnemonic(mnemonic)
    console.log(``,HDNode)
    // 2. 通过HD钱包派生20钱包
    const numWallet = 20
    // 派生路经 m/purpose'/conin_type'/account'/change/address_index
    let basePath = "m/44'/60'/0'/0"
    const wallets:any = []
    for (let i = 0; i< numWallet; i++){
      let hdNodeNew = HDNode.derivePath(basePath + '/' + i)
      let walletNew = new ethers.Wallet(hdNodeNew.privateKey)
      console.log(`第${i+1} 个钱包地址：${walletNew.address}`)
      wallets.push(walletNew)
    }
    // 3. 保存钱包为加密json
    const wallet = ethers.Wallet.fromMnemonic(mnemonic)
    console.log(`通过助记词创建钱包`)
    console.log(wallet)
    // 加密json用的密码
    const pwd = "password"
    const json = await wallet.encrypt(pwd)
    console.log(`加密后的钱包json`)
    console.log(json)
    // 4. 解密钱包
    const wallet2 = await ethers.Wallet.fromEncryptedJson(json,pwd)
    console.log(`从加密的钱包创建实例`)
    console.log(wallet2)
  }
  main()
}